<?php

class ProductController extends DefaultModuleController {
	
	public function actionDetail() {
		$categoryId = getgpc(2);
		if(getgpc('verify', 'G')=='islogin' && !$this->userId) {
			$tourl = getgpc('tourl','G');
			$this->message('您如果是'.GODHOUSE_COMPANYNAME.'用户，请您<a href="site-login.htm?tourl='.urlencode($tourl).'" style="color:red">登录</a>后购买，否则请<a href="site-register.htm?tourl='.urlencode($tourl).'" style="color:red">注册</a>');
		}

		if(getgpc('intoShopping', 'G')=='add' && $this->userId) {
		/*
		echo "<script>alert('施耐德产品价格上调，暂不能订货，价格更新中');history.go(-1);</script>";
		*/
			$action = getgpc('action', 'G');
			$pid = getgpc('pid', 'G');
			$pidArr = rtrim($pid, '-');
			$proidArr = explode('-', $pidArr);

			$pvalue = getgpc('pvalue', 'G');
			if(!empty($pvalue)) {
				$pvalue = rtrim($pvalue, '-');
				$pvalueArr = explode('-', $pvalue);
			}
			
			foreach($proidArr as $key => $val){
				if(empty($val) || !is_numeric($val)) continue;
				$pAmount = is_numeric($pvalueArr[$key]) && isset($pvalueArr[$key]) && $pvalueArr[$key] > 0 ? $pvalueArr[$key] : 1;
				if($this->ShoppingcartModel->count("userid = '$this->userId' AND productId='$val' AND settleStatus=0")==0) {
					if($prArr = $this->ProductModel->find("productId='$val'")) {
						$this->ShoppingcartModel->insert(array(
						'userId'=>$this->userId,
						'productId'=>$val,
						'cartCount'=>$pAmount,
						'ourPrice'=>$prArr['ourPrice'],
						'promotionsPrice'=>($prArr['ispromotions']==1?$prArr['promotionsPrice']:0),
						'ispromotions'=>$prArr['ispromotions'],
						'discount'=>($prArr['ispromotions']==1 ? 0 : $this->getDiscount($prArr['upperparentId'], $prArr['parentId'])),						
						'time'=>$this->time));
					}
				} else {
					$this->ShoppingcartModel->update("userId = '$this->userId' AND productId='$val' AND settleStatus=0", array('cartCount'=>"+$pAmount"));
				}
			}
			
			if($action && $action == 'now') $this->redirect('cart.htm');

			$cartArr = $this->_totalPrice();
			$this->message($this->_shoppingInfo($cartArr['cartCount'], $cartArr['totalPrice']));
		}

		if(!$categoryId || !is_numeric($categoryId)) {
			$this->message('对不起，没有这个系列的产品！','product-list.htm');
		}

		$page = max(1, getgpc('page'));
		$num = $this->ProductModel->count("ispromotions='0' AND categoryId='$categoryId'");
		$multipage = $this->page($num, GODHOUSE_PPP, $page, "product-detail-$categoryId.htm");
		$productArr = $this->ProductModel->findAll("ispromotions='0' AND categoryId='$categoryId'", $page, GODHOUSE_PPP," productSort asc");
		foreach($productArr as &$v) {
			$category =	$this->CategoryModel->findByPk($v['categoryId']);
			$v['categoryName'] = $category['cateName'];
			$v['userPrice'] = $this->userId ? number_format($v['ourPrice']*$this->getDiscount($v['upperparentId'], $v['parentId']), 2, '.', '') : '未登录';
			$v['contents'] = cutstr($v['content'], '20', '');
		}
		
		$oneArr = $this->CategoryModel->find("categoryId='$categoryId'");
		$toArr = $this->CategoryModel->find("categoryId=".$oneArr['parentId']."");
		
		$oneArr['content']=nl2br($oneArr['content']);
		//$this->header['title'].=' - '.$oneArr['cateName'];
		
		$categorysArr = $this->CategorysPublic->get_list(GODHOUSE_CATEGORY_PRODUCT);
		foreach ($categorysArr as $key => &$v) {
			$v['cateName'] = cutstr($v['cateName'], 18, '');
		}
		$this->view->assign('leftListArr', $categorysArr);
		
		
		$this->header['title'] = $oneArr['cateName']."-".$this->header['title'];
		$this->view->assign('oneArr', $oneArr);
		$this->view->assign('toArr', $toArr);
		$this->view->assign('productArr', $productArr);
		$this->view->assign('cateArr', $this->_showCategory());
		$this->view->assign('multipage', $multipage);
		$this->view->assign('numCount', $num);
		$this->view->assign('categoryId', $oneArr['parentId']);
		$this->display('product_detail');
	}

	public function actionComparison() {
		$page = max(1, getgpc('page'));
		$productId = '';
		$comparisonProdcut = getgpc('listhc','C');
		$cpArr = explode('/', $comparisonProdcut);
		foreach($cpArr as $val) {
			$cpId = explode('_', $val);
			if(is_numeric($cpId[0])) {
				$productId .= $cpId[0].',';
			}
		}

		if(!empty($productId)) {
			$sqlstr = "productId in (".rtrim($productId,',').")";
		}
		
		$num = $this->ProductModel->count($sqlstr);
		$multipage = $this->page($num, GODHOUSE_PRODUCT_PPP, $page, "product_comparison.htm");
		$productArr = $this->ProductModel->findAll($sqlstr, $page, GODHOUSE_PRODUCT_PPP);
		foreach($productArr as &$v) {
			$v['userPrice'] = $this->userId ? number_format($v['ourPrice']*$this->getDiscount($v['upperparentId'], $v['parentId']), 2, '.', '') : '未登录';
			$v['contents'] = cutstr($v['content'], '20', '');
		}

		$this->view->assign('numCount', $num);
		$this->view->assign('multipage', $multipage);
		$this->view->assign('productArr', $productArr);
		$this->view->assign('cateArr', $this->_showCategory());
		$this->view->assign('categoryId', $oneArr['parentId']);
		$this->display('product_comparison');
	}
	
	public function actionSerchDetail() {		
		$keyword = getgpc('keyword', 'G');
		$categoryId = getgpc('categoryId', 'G');
		$letter = getgpc('letter', 'G');
		
		$keys = explode(" ", $keyword);
		$sqladd = "";
		
		$sqladd = "ispromotions='0' AND ";
		if(preg_match('/^([\d]+)_([\d]+)$/', $categoryId, $cateArr)){
			$sqladd .= ($cateArr[2]==1?'upperparentId':($cateArr[2]==2?'parentId':'categoryId'))."='{$cateArr[1]}' AND ";
		}
		
		if(preg_match('/^[A-Z]+?$/', strtoupper($letter))){
			$sqladd .= "letterSort = '$letter' AND ";
		}
		
		foreach ($keys as $k=>$v){
			$sqladd.=" (content like '%".$v."%'  or productNo like '%".$v."%')  AND";
		}
		
		if($sqladd) {
			$sqladd = substr($sqladd, 0, -3);
		}
		

		$page = max(1, getgpc('page'));
		$num = $this->ProductModel->count($sqladd);
		$multipage = $this->page($num, GODHOUSE_PRODUCT_PPP, $page, "product-serchdetail.htm?letter=$letter&categoryId=$categoryId&keyword=$keyword");
		$productArr = $this->ProductModel->findAll($sqladd, $page, GODHOUSE_PRODUCT_PPP);
		
		foreach($productArr as &$v) {
			$content = $v['content'];
			foreach($keys as $vs) {
			
			$content = str_ireplace("$vs", "$vs", $content);
			
			}
			//echo $content;
			
			$category =	$this->CategoryModel->findByPk($v['categoryId']);
			$v['categoryName'] = $category['cateName'];
			$v['userPrice'] = $this->userId ? number_format($v['ourPrice']*$this->getDiscount($v['upperparentId'], $v['parentId']), 2, '.', '') : '未登录';
			$v['content'] = $content;
			
		}
		
		
		$this->view->assign('keyword', $keyword);
		$this->view->assign('numCount', $num);
		$this->view->assign('multipage', $multipage);
		$this->view->assign('productArr', $productArr);
		$this->view->assign('cateArr', $this->_showCategory());
		$this->view->assign('categoryId', $oneArr['parentId']);
		$this->view->assign('letter', $letter);
		$this->display('product_serchdetail');
	}

	public function actionPromotions() {
		$page = max(1, getgpc('page'));
		$today = strtotime(date('Y-m-d'));
		
		$sqlstr = "ispromotions='1' AND startDate<='$today' AND endDate>='$today'";
		$num = $this->ProductModel->count($sqlstr);
		$multipage = $this->page($num, GODHOUSE_PRODUCT_PPP, $page, "product_promotions.htm");
		$productArr = $this->ProductModel->findAll($sqlstr, $page, GODHOUSE_PRODUCT_PPP);
		foreach($productArr as &$v) {
			$v['userPrice'] = $this->userId ? number_format($v['ourPrice']*$this->getDiscount($v['upperparentId'], $v['parentId']), 2, '.', '') : '未登录';
			$v['contents'] = cutstr($v['content'], '20', '');
		}

		$this->view->assign('numCount', $num);
		$this->view->assign('multipage', $multipage);
		$this->view->assign('productArr', $productArr);
		$this->view->assign('cateArr', $this->_showCategory());
		$this->display('product_promotions');
	}
	
	public function actionList() {
		$pagestr = $sqladd = '';

		$page = max(1, getgpc('page'));
		$orderby = getgpc('orderby', 'G');
		$categoryId = (int)getgpc(2);
		$big = getgpc(3);
		$cid = getgpc('cid', 'G');
		$pname = getgpc('pname', 'G');

		if(empty($categoryId)) {
			$sqladd = "storeId = '".GODHOUSE_CATEGORY_PRODUCT."' AND parentId='0'  ";
			$big = 'big';
		} elseif (!is_numeric($categoryId)) {
			$this->message('对不起，您访问的这个产品已经下线了！','product-list.htm');
		} else {
			$pagestr = "-$categoryId";
			if($big=='big')$pagestr .= '-big';
			$sqladd =  "storeId = '".GODHOUSE_CATEGORY_PRODUCT."' AND parentId='$categoryId'  ";
		}
		
		$num = $this->CategoryModel->count($sqladd);
		$multipage = $this->page($num, GODHOUSE_PRODUCT_PPP, $page, "product-list$pagestr.htm");
		$products = $this->CategoryModel->fetchAll($sqladd, $page, GODHOUSE_PRODUCT_PPP, "cateSort ASC");
		foreach($products as &$v) {
			$v['altCateName'] = $v['cateName'];
			$v['cateName'] = cutstr($v['cateName'],'18');
			$v['content'] = cutstr($v['content'],'70');
		}
		
		/*[0] => Array
        (
            [categoryId] => 15
            [parentId] => 0
            [child] => 88
            [cateName] => 微型断路器
            [level] => 1
            [isMenu] => 0
            [cateSort] => 1
            [productCount] => 0
            [createdTime] => 2011-04-27
        )*/
        
		$categorysArr = $this->CategorysPublic->get_list(GODHOUSE_CATEGORY_PRODUCT);
		foreach ($categorysArr as $key => &$v) {
			$v['cateName'] = cutstr($v['cateName'], 18, '');
		}
		//print_r($categorysArr);
		$this->view->assign('leftListArr', $categorysArr);
		list($cateArr, $selectTitleCateNmae) = $this->_showCategory($categoryId,'list');
		//$this->header['title'].=' - '.$selectTitleCateNmae;
		$this->header['title'] = $selectTitleCateNmae."-".$this->header['title'];
		$this->view->assign('cateArr', $cateArr);
		$this->view->assign('multipage', $multipage);
		$this->view->assign('products', $products);
		$this->view->assign('numCount', $num);
		$this->view->assign('categoryId', $categoryId);
		$this->view->assign('prourl', !empty($big)?'list':'detail');
		$this->view->assign('big', empty($categoryId)?"-$big":'');
		$this->display('product_list');
	}

	public function actionGuide() {
		list($cateArr, $selectTitleCateNmae) = $this->_showCategory($categoryId,'list');
		$this->view->assign('cateArr', $cateArr);
		$this->display('guide');
	}
		
	private function _showCategory($categoryId=0,$type='') {
		$listArr = $this->CategorysPublic->get_list(GODHOUSE_CATEGORY_PRODUCT, 2);
		$selectName = '';
		
		foreach ($listArr as $key => $val) {
			if($categoryId==$val['categoryId']) {
				$selectName = $val['cateName'];
			}			
			if($val['level']==1) {
				$strArr = array();
				foreach ($listArr as $oval) {
					if($oval['parentId']==$val['categoryId']) {
						$strArr[] = array('categoryId' => $oval['categoryId'], '_cateName' => $oval['cateName'], 'cateName' => cutstr($oval['cateName'], 18, ''), 'productCount' => $oval['productCount']);
					}
				}
				$mlistArr[] = array('categoryId' => $val['categoryId'], 'cateName' => $val['cateName'], 'moreArr' => $strArr);
			}
        }
		return $type=='list'?array($mlistArr, $selectName):$mlistArr;
	}

	private function _shoppingInfo($cartCount,$totalPrice) {
	/*
	echo "<script>alert('施耐德产品价格上调，暂不能订货，价格更新中');history.go(-1);</script>";
	exit;
	*/
		return '
		<div style="width:402px; height:112px; background-image:url(images/T1YNR0Xk8sXXXXXXXX-637-153.png)">
			<table width="100%" height="107" border="0" cellpadding="0" cellspacing="0">
				<tr>
					<td width="15%"></td>
					<td width="85%"><h4>产品已成功添加到购物车！</h4></td>
				</tr>
				<tr>
					<td></td>
					<td id="ShopcartCount"><p>购物车共有<b>'.$cartCount.'</b>种产品，合计：<b><font color="#FE6500">'.$totalPrice.'</font></b>元</p></td>
				</tr>
				<tr>
					<td></td>
					<td>
						<table><tr><td>
						<a style="display:block; width:87px; height:25px; line-height:25px; padding-left:13px; font-size:12px; color:#ffffff;background-image:url(images/default/003.gif)" href="/cart.htm" title="去购物车结算">去购物车结算</a>
						</td><td><a href="#1" onclick="hidemenu(\''.getgpc('menuid').'\');" title="再逛逛">再逛逛</a></td></tr></table>
					</td>
				</tr>
			</table>
		</div>';
	}
}
